<?php

namespace App\Http\Controllers\UserCenter;

use App\Http\Controllers\Component\MasterResponseController;
use App\Model\Creator;
use App\Model\Goods;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Model\Order;
use Auth;
use DB;
use Illuminate\Support\Facades\Redis;
use phpDocumentor\Reflection\Types\Array_;
use phpDocumentor\Reflection\Types\Parent_;
use PhpParser\Node\Expr\New_;
use Webpatser\Uuid\Uuid;


class MyDealController extends MasterResponseController
{

    public function __construct()
    {
        $this->middleware('isCreator'); //当前用户是否登录且为创作者
    }

    public function index()
    {

        $userId = Auth::user()->id;
//        $creatorId=Creator::where('user_id',$userId)->value('id');
        //正在进行订单  （已付款，已发货）
        $orderOfOngoing = Order::rightJoin('goods_v', function ($join) use ($userId) {
            $join->on('goods_v.id', '=', 'orders.goods_id')
                ->where('goods_v.user_id', '=', $userId);
        })->leftJoin('china_region', 'china_region.town_id', 'orders.town_id')
            ->select(
                'orders.*',
                'china_region.province_name as province',
                'china_region.city_name as city',
                'china_region.county_name as county',
                'china_region.town_name as region',
                'goods_v.name as goods_name',
                'goods_v.author as author',
                'goods_v.price as price',
                'goods_v.size as size',
                'goods_v.genre as genre',
                'goods_v.imgUrl as imgUrl'
            )
            ->where(function ($query) {
                $query->where('orders.status', '=', 1)
                    ->orWhere('orders.status', '=', 2);
            })
            ->orderBy('orders.created_at', 'desc')
            ->get();

        //申请退款/退货订单 （退款|退款退货）
        $ordersOfRefundAndReturn = Order::rightJoin('goods_v', function ($join) use ($userId) {
            $join->on('goods_v.id', '=', 'orders.goods_id')
                ->where('goods_v.user_id', '=', $userId);
        })->leftJoin('china_region', 'china_region.town_id', 'orders.town_id')
            ->select(
                'orders.*',
                'china_region.province_name as province',
                'china_region.city_name as city',
                'china_region.county_name as county',
                'china_region.town_name as region',
                'goods_v.name as goods_name',
                'goods_v.author as author',
                'goods_v.price as price',
                'goods_v.size as size',
                'goods_v.genre as genre',
                'goods_v.imgUrl as imgUrl'
            )
            ->where(function ($query) {
                $query->where('orders.status', '=', 100)
                    ->orWhere('orders.status', '=', 200);
            })
            ->orderBy('orders.created_at', 'desc')
            ->get();

        //已完成订单
        $ordersOfDone = Order::rightJoin('goods_v', function ($join) use ($userId) {
            $join->on('goods_v.id', '=', 'orders.goods_id')
                ->where('goods_v.user_id', '=', $userId);
        })->leftJoin('china_region', 'china_region.town_id', 'orders.town_id')
            ->select(
                'orders.*',
                'china_region.province_name as province',
                'china_region.city_name as city',
                'china_region.county_name as county',
                'china_region.town_name as region',
                'goods_v.name as goods_name',
                'goods_v.author as author',
                'goods_v.price as price',
                'goods_v.size as size',
                'goods_v.genre as genre',
                'goods_v.imgUrl as imgUrl'
            )
            ->where('orders.status', '=', 4)
            ->orderBy('orders.created_at', 'desc')
            ->get();

        //已关闭订单
        $ordersOfClose = Order::rightJoin('goods_v', function ($join) use ($userId) {
            $join->on('goods_v.id', '=', 'orders.goods_id')
                ->where('goods_v.user_id', '=', $userId);
        })->leftJoin('china_region', 'china_region.town_id', 'orders.town_id')
            ->select(
                'orders.*',
                'china_region.province_name as province',
                'china_region.city_name as city',
                'china_region.county_name as county',
                'china_region.town_name as region',
                'goods_v.name as goods_name',
                'goods_v.author as author',
                'goods_v.price as price',
                'goods_v.size as size',
                'goods_v.genre as genre',
                'goods_v.imgUrl as imgUrl'
            )
            ->where('orders.status', '=', 5)
            ->orderBy('orders.created_at', 'desc')
            ->get();

        $data = array(
            'ordersOfOngoing' => $orderOfOngoing,
            'ordersOfRefundAndReturn' => $ordersOfRefundAndReturn,
            'ordersOfDone' => $ordersOfDone,
            'ordersOfClose' => $ordersOfClose,
        );
        return view('user_center.myDeal', compact('data'));
    }

    //已发货
    public function delivered(Request $request)
    {
        $key=$request['id'];
        $random=Uuid::generate(4);
        $ttl=100000;
        $redis=Redis::connection('redis-order');
        $ok=$redis->set($key,$random,'px',$ttl,'nx');
        if ($ok){
            $time=Carbon::now();
           $order= Order::where('id',$key)->first();
           if ($order->status==1){
               $order->status=2;
               $order->delivery_time=$time;
               $order->save();
               if ($redis->get($key)==$random){
                   $redis->del($key);
               }
               $message='订单状态已修改为已发货';
               return parent::successWithData($message,$time->toDateTimeString());
           }else{
               if ($redis->get($key)==$random){
                   $redis->del($key);
               }
               return parent::error('此交易客户已申请退款');
           }
        }else{
            return parent::error('服务器繁忙或当前订单正在被客户进行操作！，请稍后再试');
        }
    }

    //处理退款申请
    public function confirmRefunded(Request $request)
    {
        $time = Carbon::now();
        Order::where('id', $request['id'])
            ->update([
                'status' => '5',
                'refunded_time' => $time,
            ]);

        Goods::where('id',$request['goods_id'])
            ->update([
                'status'=>1
            ]);
        $message = '退款申请已处理！';
        return parent::successWithData($message, $time->toDateTimeString());

    }

    //处理退款退货申请
    public function confirmRefundedAndReturn(Request $request)
    {
        $time=Carbon::now();
        Order::where('id',$request['id'])
            ->update([
                'status'=>'5',
                'refunded_return_time'=>$time,
            ]);

        Goods::where('id',$request['goods_id'])
            ->update([
                'status'=>1
            ]);
        $message='退款退货申请已处理！';
        return parent::successWithData($message,$time->toDateTimeString());
    }
}
